package cn.bone.base.component;

import cn.bone.base.bean.CommonResult;
import cn.bone.base.bean.RequestInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;


@ControllerAdvice
@Slf4j
public class ResultAdvice implements ResponseBodyAdvice<CommonResult> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {

        //只有返回值类型为CommonResult的时候，才会处理
        return returnType.getParameterType().getName()
                .equalsIgnoreCase(CommonResult.class.getName());
    }

    @Override
    public CommonResult beforeBodyWrite(CommonResult body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {

        RequestInfo requestInfo = RequestInfo.get();
        if(requestInfo!=null && body!=null){
            requestInfo.setCode(body.getCode());
            body.setRequestId(requestInfo.getRequestId());
        }
        return body;
    }
}
